var $parentNode = window.parent.document;

function $childNode(name) {
    return window.frames[name]
}

// tooltips
// $('.tooltip-demo').tooltip({
//     selector: "[data-toggle=tooltip]",
//     container: "body"
// });

// 使用animation.css修改Bootstrap Modal
$('.modal').appendTo("body");

// $("[data-toggle=popover]").popover();

//折叠ibox
$('.collapse-link').click(function () {
    var ibox = $(this).closest('div.ibox');
    var button = $(this).find('i');
    var content = ibox.find('div.ibox-content');
    content.slideToggle(200);
    button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');
    ibox.toggleClass('').toggleClass('border-bottom');
    setTimeout(function () {
        ibox.resize();
        ibox.find('[id^=map-]').resize();
    }, 50);
});

//关闭ibox
$('.close-link').click(function () {
    var content = $(this).closest('div.ibox');
    content.remove();
});

//判断当前页面是否在iframe中
//if (top == this) {
//    var gohome = '<div class="gohome"><a class="animated bounceInUp" href="index.html?v=4.0" title="返回首页"><i class="fa fa-home"></i></a></div>';
//    $('body').append(gohome);
//}

//animation.css
function animationHover(element, animation) {
    element = $(element);
    element.hover(
        function () {
            element.addClass('animated ' + animation);
        },
        function () {
            //动画完成之前移除class
            window.setTimeout(function () {
                element.removeClass('animated ' + animation);
            }, 2000);
        });
}

//拖动面板
function WinMove() {
    var element = "[class*=col]";
    var handle = ".ibox-title";
    var connect = "[class*=col]";
    $(element).sortable({
            handle: handle,
            connectWith: connect,
            tolerance: 'pointer',
            forcePlaceholderSize: true,
            opacity: 0.8,
        })
        .disableSelection();
};


//编辑器新增的ajax上传图片函数
function sendFile(files, editor, $editable) {
    var formData = new FormData();
    formData.append("file", files[0]);
    $.ajax({
        data : formData,
        type : "POST",
        url : "/common/sysFile/upload",    // 图片上传出来的url，返回的是图片上传后的路径，http格式
        cache : false,
        contentType : false,
        processData : false,
        dataType : "json",
        success: function(data) {//data是返回的hash,key之类的值，key是定义的文件名
            $('.summernote').summernote('insertImage',data.data);
        },
        error:function(data){
            //console.log("data",data)
            alert("上传失败");
        }
    });
}

//计算带中文的字符串显示宽度
function lengthCN(message) {
    var strlenght = 0;
    var txtval = $.trim(message);
    for (var i = 0; i < txtval.length; i++) {
        if (isCN(txtval.charAt(i)) == true) {
            strlenght = strlenght + 1.8;
        } else {
            strlenght = strlenght + 1;
        }
    }
    return strlenght;
}
function isCN(str) {
	var regexCh = /[u00-uff]/;
	return !regexCh .test(str);
}

//预览图片
function preview(url) {
    layer.open({
        type: 1,
        title: '预览',
        closeBtn: 1,
        area: [ '800px', '800px' ],
        skin: 'layui-layer-nobg', //没有背景色
        shadeClose: true,
        offset: 't',
        content: '<img width="90%" src="'+url+'"/>'
    });
}


//通过文件路径截取名称
function subFileName(fileUrl) {
    if(fileUrl==null)return "";
    var index = fileUrl .lastIndexOf("\/");
    fileUrl  = fileUrl .substring(index + 1, fileUrl .length);
    return fileUrl
}

//表单退回
function returnInfo(prefix) {
    var rows = $('#exampleTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要退回的数据");
        return;
    }
    var ids = new Array();
    // 遍历所有选择的行数据，取每条数据对应的ID
    $.each(rows, function (i, row) {
        ids[i] = row['id'];
    });
    layer.confirm("确认要退回选中的'" + rows.length + "'条数据吗?", {
        btn: ['确认退回'],
        btn1:function(){
            console.log("yes");
            $.ajax({
                type: 'POST',
                data: {
                    "ids": ids
                },
                url: prefix + '/review',
                success: function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg);
                        reLoad();
                    } else {
                        layer.msg(r.msg);
                    }
                }
            });
        }
    });
}

//批量审核
function examine(prefix) {
    var rows = $('#exampleTable').bootstrapTable('getSelections'); // 返回所有选择的行，当没有选择的记录时，返回一个空数组
    if (rows.length == 0) {
        layer.msg("请选择要审核的数据");
        return;
    }
    var ids = new Array();
    // 遍历所有选择的行数据，取每条数据对应的ID
    $.each(rows, function (i, row) {
        ids[i] = row['id'];
    });
    layer.confirm("确认要审核选中的'" + rows.length + "'条数据吗?", {
        btn: ['通过', '不通过'],
        btn1:function(){
            console.log("yes");
            $.ajax({
                type: 'POST',
                data: {
                    "ids": ids,
                    state:1,
                    remark:""
                },
                url: prefix + '/review',
                success: function (r) {
                    if (r.code == 0) {
                        layer.msg(r.msg);
                        reLoad();
                    } else {
                        layer.msg(r.msg);
                    }
                }
            });
        },
        btn2:function(pass, index){
            layer.prompt({title: '请对这' + rows.length + '条数据填写未通过意见，并确认：', formType: 2}, function(remark, index){
                console.log("pass",remark);
                $.ajax({
                    type: 'POST',
                    data: {
                        "ids": ids,
                        state:2,
                        remark:remark
                    },
                    url: prefix + '/review',
                    success: function (r) {
                        if (r.code == 0) {
                            layer.msg(r.msg);
                            reLoad();
                        } else {
                            layer.msg(r.msg);
                        }
                    }
                });
                layer.closeAll();

            });
            return  false
    }
    });
}

//下载导入模板
function downExcelModel(table) {
    layer.confirm('您确定要下载导入模板吗？', {
        btn1:function(index){
            window.location.href = table;
            layer.close(index)
    }
    });
}


//导入
function importExcel(fileObj, formObj,cbatchId,orgId,url) {
    if (cbatchId==null||cbatchId==''){
        layer.msg('请选择认证批次后导入!');
    }else {
        var fileUrl = fileObj.val();
        var suffix = fileUrl.substr(fileUrl.lastIndexOf(".")).toLowerCase();//获得文件后缀名
        if (suffix == '.xls' || suffix == '.xlsx') {
            if (fileUrl) {
                formObj.ajaxSubmit({
                    type: "post",
                    url: url,
                    data: {cbatchId: cbatchId,orgId:orgId},
                    dataType: "json",
                    success: function (data) {
                        console.log("data",data);
                        if (data.code == 0) {
                            layer.msg(data.msg);
                            $('#exampleTable').bootstrapTable('refresh');
                        } else if (data.code ==41304 ) {
                            layer.confirm('是否下载错误报告？', {
                                btn1:function(index){
                                    window.location.href = '/jzweb/stuSignUp/importError';
                                    layer.close(index)
                                }
                            });
                        } else{
                            layer.msg(data.msg);
                        }
                    }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest, textStatus, errorThrown)
                        layer.msg('出错了!');
                    }
                });
            } else {
                layer.msg('上传的文件不可为空');
                // parent.$.messager.alert('警告', "上传的文件不可为空", 'warning');
            }
        } else {
            layer.msg('请上传正确的Excel表格!');
            // $.messager.alert('警告', "", 'warning');
        }
    }
}

//导入
function importComExcel(fileObj, formObj,cbatchId,url) {
    if (cbatchId==null||cbatchId==''){
        layer.msg('请选择考试批次后导入!');
    }else {
        var fileUrl = fileObj.val();
        var suffix = fileUrl.substr(fileUrl.lastIndexOf(".")).toLowerCase();//获得文件后缀名
        if (suffix == '.xls' || suffix == '.xlsx') {
            if (fileUrl) {
                formObj.ajaxSubmit({
                    type: "post",
                    url: url,
                    data: {cbatchId: cbatchId},
                    dataType: "json",
                    success: function (data) {
                        console.log("data",data);
                        if (data.code == 0) {
                            layer.msg(data.msg);
                            $('#exampleTable').bootstrapTable('refresh');
                        } else if (data.code ==41304 ) {
                            layer.confirm('是否下载错误报告？', {
                                btn1:function(index){
                                    window.location.href = '/jzweb/stuSignUp/importComError';
                                    layer.close(index)
                                }
                            });
                        } else{
                            layer.msg(data.msg);
                        }
                    }, error: function (XMLHttpRequest, textStatus, errorThrown) {
                        console.log(XMLHttpRequest, textStatus, errorThrown)
                        layer.msg('出错了!');
                    }
                });
            } else {
                layer.msg('上传的文件不可为空');
                // parent.$.messager.alert('警告', "上传的文件不可为空", 'warning');
            }
        } else {
            layer.msg('请上传正确的Excel表格!');
            // $.messager.alert('警告', "", 'warning');
        }
    }
}


//设置select
function selectInput(id,layero){
    //myselect1
    console.log('myselectid',id)
    let mydl=layero.find(`#${id}`).next().find('.layui-anim-upbit')
    let myinput=layero.find(`#${id}`).next().find('input')

    mydl.css('height','220px');
    let mydd=mydl.find('dd')
    //分页设置
    let size=5, totle=mydd.length,page=1,isseach=false;
    let pageSum=Math.ceil( totle/ size);
    let oldpageSum=pageSum, oldepage=page;

    //全部隐藏
    const addHidden=()=>{
        mydd.each((index)=>{
            mydd[index].classList.add("hidden")
        })
    }
    addHidden()
    //获取数据
    const gethtml= async (page,size)=>{
        //去除前
        await addHidden()
        //这个地方要考虑搜索
        let hideList=mydl.find('dd.layui-hide')
        console.log('点击',hideList.length)
        if(hideList.length>0){
            let num=0
            mydd.each(index=>{
                if(mydd[index].className.indexOf('layui-hide')<0){
                    num++;
                    if(num>=(page-1)*size && num<size*page){
                        mydd[index].classList.remove('hidden')
                    }
                }
            })

        }else{
            for (let i = (page-1)*size; i < size*page; i++) {
                mydd[i]?.classList.remove('hidden')
            }
        }
        //判断是不是
        if(!mydl[0].querySelector('div.mydivSelect')){
            mydl[0].appendChild(getPageSize())
        }else{
            //修改page
            mydl[0].querySelector('span.mydivSelectSpan1').textContent =`第${page}页(共${pageSum}页)`
        }
    }
    //分页
    const getPageSize=()=>{
        var div = document.createElement("div");
        div.className='mydivSelect'
        div.style.width='100%'
        div.style.height='30px'
        div.style.position='absolute'
        div.style.bottom='0'
        div.style.display='flex'
        div.style.styleflexDirection='row'
        div.style.stylealignItems='center'
        div.style.justifyContent='center'

        var pre=document.createElement("button")
        pre.textContent =`上一页`
        pre.style.margin= '0 10px'
        pre.style.border= '0'
        pre.style.background='transparent'
        pre.addEventListener('click',(evl)=>{
            evl.stopPropagation();
            evl.preventDefault();
            console.log('点击')
            if(page>1){
                page=page-1
                gethtml(page,size)
            }
        })

        var span1=document.createElement("span");
        span1.textContent =`第${page}页(共${pageSum}页)`
        span1.className='mydivSelectSpan1'
        span1.style.lineHeight='30px';
        var nex=document.createElement("button")
        nex.textContent =`下一页`
        nex.style.margin= '0 10px'
        nex.style.border= '0'
        nex.style.background='transparent'
        nex.addEventListener('click',(evl)=>{
            evl.stopPropagation();
            evl.preventDefault();
            console.log('点击')
            if((page+1)<=pageSum){
                page=page+1
                gethtml(page,size)
            }
        })

        div.appendChild(pre)
        div.appendChild(span1)
        div.appendChild(nex)
        return div
    }

    gethtml(page,size)

    console.log('myinput[0]',layero.find(`#${id}`).next())
    //输入框监听
    myinput[0].addEventListener('input',async (data)=>{
        let inputvalue=$(myinput[0]).val()
        console.log(inputvalue,'监听修改');
        if(null==inputvalue||''==inputvalue){
            page=oldepage
            pageSum=oldpageSum
            gethtml(page,size)
            isisseach=false
        }else{
            await addHidden()
            isseach=true
            //等待
            setTimeout(()=>{
                mydd=mydl.find('dd')
                //首先得到所有其他的
                let newtotal=0
                mydd.each(index=>{
                    if(mydd[index].className.indexOf('layui-hide')<0){
                        newtotal++;
                        //要考虑分页
                        if(newtotal<=size){
                            mydd[index].classList.remove('hidden')
                        }
                    }
                })
                // //记录老的
                oldpageSum=pageSum
                oldepage=page
                page=1
                pageSum=Math.ceil( newtotal/ size)
                //修改分页的内容
                mydl[0].querySelector('span.mydivSelectSpan1').textContent =`第${page}页(共${pageSum}页)`
            },200)

        }


    })
    myinput[0].addEventListener('click',()=>{
        //清空
        console.log('点击',isseach,size)
        setTimeout(()=>{
            if(isseach){
                //得到目前选中的范围,也就是page
                let inputvalue=$(myinput[0]).val(),pageindex=0;
                mydd.each(index=>{
                    if(mydd[index].innerHTML==inputvalue){
                        pageindex=index
                    }
                })
                //判断page位置
                let number=1;
                while (pageindex>=number*size){
                    number++;
                }
                page=number
                pageSum=Math.ceil( totle/ size)
                gethtml(page,size)
            }
        },100)

    })
}